﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class CustomerEquipment : System.Web.UI.Page
    {
        private string _docEntry = string.Empty;
        private string _poNo = string.Empty;
        private string _isPO = string.Empty; //1: PO, 0: Draft
        private string _companyCode = string.Empty;
        private string _status = string.Empty;

        private void loadPseudoData() {
         DataTable dt = new DataTable();
         dt.Columns.Add("Date");
            dt.Columns.Add("Time");
            dt.Columns.Add("HandledBy");
            dt.Columns.Add("ActivitieDate");
            dt.Columns.Add("Recurrence");
            dt.Columns.Add("Content");
            dt.Rows.Add("02/18/2014", "14:55", "Jayson Butler", "02/18/2014", "None", "");
            dt.Rows.Add("02/18/2014", "15:55", "Jayson Butler", "02/18/2014", "None", "");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            loadPseudoData();

            /*Response.Cache.SetCacheability(HttpCacheability.Private);
            if (Session[Utils.AppConstants.UserCode] == null
             || Session[Utils.AppConstants.CompanyName] == null
             || Session[Utils.AppConstants.CompanyCode] == null
              || Session[Utils.AppConstants.OutletCode] == null
                || Session[Utils.AppConstants.OutletName] == null
               || Session[Utils.AppConstants.IsSupperUser] == null
              || Session[Utils.AppConstants.Pwd] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            _isPO = Request.QueryString["IsPO"];
            _poNo = Request.QueryString["PONo"];
            _status = Request.QueryString["Status"];
            if (Session[Utils.AppConstants.CompanyCode] != null)
            {
                _companyCode = Session[Utils.AppConstants.CompanyCode].ToString();
                if (Session[Utils.AppConstants.CompanyCode] != null && Request.QueryString["CompanyCode"] != null)
                {
                    string companyCode = Request.QueryString["CompanyCode"].ToString();
                    if (Session[Utils.AppConstants.IsSupperUser].ToString().ToUpper() == "Y")
                    {
                        _companyCode = companyCode;
                    }
                }
                this.lblPoNo.Text = _poNo;
                if (_isPO == null || _isPO.Length == 0)
                {
                    Response.Redirect("ErrorPage.aspx");
                }
                if (Request.QueryString["Create"] == null)
                {
                    _docEntry = Request.QueryString["DocEntry"];
                    if (_docEntry == null || _docEntry.Length == 0)
                    {
                        Response.Redirect("ErrorPage.aspx");
                    }
                    if (!Utils.AppConstants.isInteger(_docEntry))
                    {
                        Response.Redirect("ErrorPage.aspx");
                    }
                }
                else
                {
                    this.btnCancel.Visible = false;
                    this.btnClose.Visible = false;
                }
                if (_isPO == "1" && Request.QueryString["Create"] == null)
                {

                    this.btnSaveDraft.Visible = false;
                    this.btnUpdate.Text = "Update PO";
                    this.lblTitle.Text = "View Purchase Order";
                    this.grvPO.Columns[9].Visible = true;
                    this.grvPO.Columns[10].Visible = true;
                    this.btnShowPopup.Enabled = true;
                    this.lblStatus.Text = _status;

                }
                else if (_isPO == "0" && Request.QueryString["Create"] == null)
                {
                    this.btnCancel.Text = "Delete Draft";
                    this.btnClose.Visible = false;
                    this.btnSaveDraft.Text = "Update As Draft";
                    this.btnUpdate.Text = "Send to HQ";
                    this.lblTitle.Text = "Update Draft PO";
                    this.lblStatus.Text = _status;
                }
                if (!IsPostBack)
                {
                    LoadOrderWareHouse();
                    if (Request.QueryString["DocEntry"] != null && Request.QueryString["DocEntry"].ToString().Length > 0)
                    {
                        //Set Update Process
                        this.hdnIsUpdate.Value = "1";
                        this.btnSelectVendor.Visible = false;
                        this.txtVendorName.Enabled = false;

                        LoadData(_docEntry, _isPO);
                    }
                    else
                    {
                        //Set Create New Process
                        this.hdnIsUpdate.Value = "0";
                        this.btnSaveDraft.Enabled = false;
                        this.btnUpdate.Enabled = false;
                        this.txtDelDate.Text = DateTime.Now.Date.ToString(Utils.AppConstants.DATE);
                        this.txtPODate.Text = DateTime.Now.Date.ToString(Utils.AppConstants.DATE);
                        Session["ChosenItem"] = null;
                        Session["OrderWareHouse"] = null;
                        LoadData();
                    }
                    if ((this.hdnStatus.Value == "C" || Session[Utils.AppConstants.IsSupperUser].ToString() == "N") && Request.QueryString["Create"] == null && _isPO == "1")
                    {
                        DisableControl();
                    }
                }
                if (Session[Utils.AppConstants.IsSupperUser] != null && Session[Utils.AppConstants.IsSupperUser].ToString().ToUpper() == "N" && Request.QueryString["Create"] == null && _isPO == "1")
                {
                    this.btnUpdate.Visible = false;
                    this.btnCancel.Visible = false;
                    this.btnClose.Visible = false;
                }
            }
            else
            {
                Response.Redirect("../../Login.aspx");
            }
            if (!IsPostBack)
            {
                LoadData();
            }
             */
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            
            DataTable tblIPO = (DataTable)Session["POTable"];
            BindData(tblIPO);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    
                    BindData((DataTable)Session["POTable"]);
                    CalcTotal(((DataTable)Session["POTable"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
            //    e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
            //    e.Row.Attributes["style"] = "cursor:pointer";
            //    int index = 0;
            //    TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
            //    ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
            //    if (ViewState["rowindex"] != null && Session["POTable"] != null)
            //    {
            //        index = Convert.ToInt32(ViewState["rowindex"].ToString());
            //        int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
            //    }
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        private void DisableControl()
        {
            this.btnSaveDraft.Visible = false;
            this.btnCancel.Visible = false;
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadSupplierAmount()
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }
                }

                
                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadOrderWareHouse()
        {
            try
            {
                
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        private DataRow FillShipToAddress(string outletId, bool isFill)
        {
            try
            {
                if (outletId.Length > 0)
                {
                    MasterData obj = new MasterData();
                    DataSet tbWareHouse = null; // obj.GetWareHouseAddress(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode);
                    if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
                    {

                        DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
                        if (r.Length > 0)
                        {
                            if (isFill)
                            {
                                StringBuilder shipTo = new StringBuilder();
                                shipTo.AppendLine(r[0]["Block"].ToString());
                                shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
                                shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
                            }
                            else
                            {
                                return r[0];
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            
            BindData((DataTable)Session["POTable"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            BindData((DataTable)Session["POTable"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = null;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    BindData((DataTable)Session["POTable"]);
                    CalcTotal(((DataTable)Session["POTable"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = null;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    BindData(tb);
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private DataTable CreateTabelFormat()
        {
            DataTable tbTemp = new DataTable();
            tbTemp.Columns.Add("ItemCode");
            tbTemp.Columns.Add("Dscription");
            tbTemp.Columns.Add("LB");
            tbTemp.Columns.Add("Model");
            tbTemp.Columns.Add("BuyUnitMsr");
            tbTemp.Columns.Add("Quantity");
            tbTemp.Columns.Add("ReceivedQty");
            tbTemp.Columns.Add("Price");
            tbTemp.Columns.Add("LineTotal");
            tbTemp.Columns.Add("VatgroupPu");
            tbTemp.Columns.Add("Rate");
            tbTemp.Columns.Add("ShipType");
            tbTemp.Columns.Add("TrnspName");
            tbTemp.Columns.Add("IsGRPO");
            tbTemp.Columns.Add("BalanceQty");
            return tbTemp;
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadData()
        {
            BindData(CreateTabelFormat());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["POTable"] = tblData;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = DateTime.Now;
                    DataTable tblIPO = (DataTable)Session["POTable"];
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblIPO != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    MasterData obj = new MasterData();
                                    DataSet dsItem = null;//obj.GetSupplierItemSetup(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, this.txtVendorCode.Text, "");
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow[] existRow = tblIPO.Select("ItemCode = '" + item.Key + "'");
                                        if (existRow.Length == 0)
                                        {
                                         
                                            if (dsItem != null && dsItem.Tables.Count > 0)
                                            {
                                                foreach (DataRow r in dsItem.Tables[0].Rows)
                                                {
                                                    if (r["ItemCode"].ToString() == item.Key)
                                                    {
                                                        tblIPO = AddNewItem(tblIPO, poDate, r["ItemCode"].ToString(), r["ItemName"].ToString(), r["LB"].ToString(), decimal.Parse(r["MinQty"].ToString()), decimal.Parse(r["MaxQty"].ToString()), this.txtVendorCode.Text, 0);
                                                    }
                                                }
                                            }
                                            //ReLoad Data
                                            BindData(tblIPO);
                                            if (tblIPO.Rows.Count > 0)
                                            {
                                                //Update Price
                                                UpdatePrice();
                                                CalcTotal(tblIPO);
                                            }
                                        }
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblIPO);
                            break;
                        case "SelectVendor":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            this.txtVendorCode.Text = Session["ChosenVendorCode"] != null ? Session["ChosenVendorCode"].ToString() : "";
                            this.txtVendorName.Text = Session["ChosenVendorName"] != null ? Session["ChosenVendorName"].ToString() : "";
                            if (tblIPO != null)
                            {
                                tblIPO.Rows.Clear();
                            }
                            Session["ChosenItem"] = null;
                            tblIPO = LoadSetupItem(poDate, tblIPO);
                            LoadSupplierAmount();
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="tblIPO"></param>
        /// <returns></returns>
        private DataTable LoadSetupItem(DateTime poDate, DataTable tblIPO)
        {
            MasterData obj = new MasterData();
            DataSet dsItem = null; // obj.GetSupplierItemSetup(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, this.txtVendorCode.Text, "");
            Dictionary<string, string> dicItem = new Dictionary<string, string>();
            if (dsItem != null && dsItem.Tables.Count > 0)
            {
                dsItem.Tables[0].Columns.Add("Quantity");
                DataSet dsAllPrice = null; // obj.GetAllItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, this.txtVendorCode.Text, dsItem.Tables[0]);
                foreach (DataRow r in dsItem.Tables[0].Rows)
                {
                    if (!dicItem.ContainsKey(r["ItemCode"].ToString()))
                    {
                        dicItem.Add(r["ItemCode"].ToString(), r["ItemName"].ToString());
                    }
                    if (dsAllPrice != null && dsAllPrice.Tables.Count > 0)
                    {
                        foreach (DataRow row in dsAllPrice.Tables[0].Rows)
                        {
                            if (r["ItemCode"].ToString() == row["ItemCode"].ToString())
                            {
                                DataRow rowNew = tblIPO.NewRow();
                                rowNew["ItemCode"] = r["ItemCode"].ToString();
                                rowNew["Dscription"] = r["ItemName"].ToString();
                                rowNew["LB"] = r["LB"].ToString();
                                rowNew["MinStock"] = Math.Round(decimal.Parse(r["MinQty"].ToString()), 2);
                                rowNew["MaxStock"] = Math.Round(decimal.Parse(r["MaxQty"].ToString()), 2);
                                rowNew["BuyUnitMsr"] = row["BuyUnitMsr"];
                                rowNew["Quantity"] = decimal.Parse("0").ToString("#,##0.00");
                                rowNew["ReceivedQty"] = row["ReceivedQty"];
                                if (row["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                                {
                                    rowNew["Price"] = (decimal.Parse(row["NumInBuy"].ToString()) * decimal.Parse(row["Price"].ToString())).ToString("#,##0.00");
                                }
                                else
                                {
                                    rowNew["Price"] = decimal.Parse(row["Price"].ToString()).ToString("#,##0.00");
                                }
                                rowNew["LineTotal"] = decimal.Parse(row["LineTotal"].ToString()).ToString("#,##0.00");
                                rowNew["VatgroupPu"] = row["VatgroupPu"];
                                rowNew["Rate"] = row["Rate"];
                                rowNew["ShipType"] = row["ShipType"];
                                rowNew["TrnspName"] = row["TrnspName"];
                                DataRow[] rCheck = tblIPO.Select("ItemCode='" + r["ItemCode"].ToString() + "'");
                                if (rCheck.Length == 0)
                                {
                                    tblIPO.Rows.Add(rowNew);
                                }
                            }
                        }
                    }
                    //tblIPO = AddNewItem(tblIPO, poDate, r["ItemCode"].ToString(), r["ItemName"].ToString(), r["LB"].ToString(), decimal.Parse(r["MinQty"].ToString()), decimal.Parse(r["MaxQty"].ToString()), this.txtVendorCode.Text, 0);
                }
            }
            Session["ChosenItem"] = dicItem;
            //ReLoad Data
            BindData(tblIPO);
            if (tblIPO.Rows.Count > 0)
            {
                //Update Price
                //UpdatePrice();
                CalcTotal(tblIPO);
            }
            this.btnSaveDraft.Enabled = true;
            return tblIPO;
        }
        /// <summary>
        /// 
        /// </summary>
        private void UpdatePrice()
        {
            try
            {
                //Update Price
                foreach (DataRow r in ((DataTable)Session["POTable"]).Rows)
                {
                    GetPrice(r);
                }
                BindData((DataTable)Session["POTable"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// Update Price
        /// </summary>
        /// <param name="r"></param>
        private void GetPrice(DataRow r)
        {
            try
            {
                DataSet ds = GetDataItem(DateTime.Now, r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblIPO"></param>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="itemName"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataTable AddNewItem(DataTable tblIPO, DateTime poDate, string itemCode, string itemName, string lb, decimal min, decimal max, string venderCode, double quantity)
        {
            try
            {
                DataSet ds = GetDataItem(poDate, itemCode, venderCode, quantity);
                if (ds != null && ds.Tables.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        DataRow rowNew = tblIPO.NewRow();
                        rowNew["ItemCode"] = itemCode;
                        rowNew["Dscription"] = itemName;
                        rowNew["LB"] = lb;
                        rowNew["MinStock"] = Math.Round(min, 2);
                        rowNew["MaxStock"] = Math.Round(max, 2);
                        rowNew["BuyUnitMsr"] = row["BuyUnitMsr"];
                        rowNew["Quantity"] = quantity.ToString("#,##0.00");
                        rowNew["ReceivedQty"] = row["ReceivedQty"];
                        rowNew["Price"] = decimal.Parse(row["Price"].ToString()).ToString("#,##0.00");
                        rowNew["LineTotal"] = decimal.Parse(row["LineTotal"].ToString()).ToString("#,##0.00");
                        rowNew["VatgroupPu"] = row["VatgroupPu"];
                        rowNew["Rate"] = row["Rate"];
                        rowNew["ShipType"] = row["ShipType"];
                        rowNew["TrnspName"] = row["TrnspName"];
                        DataRow[] rCheck = tblIPO.Select("ItemCode='" + itemCode + "'");
                        if (rCheck.Length == 0)
                        {
                            tblIPO.Rows.Add(rowNew);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return tblIPO;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["Rate"] != null && row["Rate"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["Rate"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
               
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        private string CheckDate()
        {
 
            return string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
               string errMess =  CheckDate();
               if (errMess.Length > 0)
               {
                   this.lblError.Text = errMess;
                   this.lblError.Visible = true;
                   return;
               }
                this.lblError.Visible = false;
                this.lblError.Text = "";
                DataSet dsData = new DataSet();
                dsData = CollectDataPO(false);
                if (dsData != null)
                {
                    MasterData obj = new MasterData();
                    DataSet dsResult = null; // obj.CreatePO(_companyCode, this.hdnIsUpdate.Value, _isPO, dsData, false, _docEntry, this.txtVendorCode.Text, "");
                    if (dsResult != null && dsResult.Tables.Count > 0 && dsResult.Tables[0].Rows.Count > 0)
                    {
                        if ((int)dsResult.Tables[0].Rows[0]["ErrCode"] != 0)
                        {
                            string err = dsResult.Tables[0].Rows[0]["ErrMsg"].ToString();
                            if (err.Trim() == "The device is not ready.")
                            {
                                err = "System is processing another request. Pls try again later.";
                            }
                            this.lblError.Text = err;
                        }
                        else
                        {
                            this.lblError.Text = "Operation complete successful!";

                            if (this.hdnIsUpdate.Value == "0")
                            {
                                ResetPage();
                            }
                            
                        }
                    }
                    else
                    {
                        this.lblError.Text = "System is processing another request. Pls try again later.";
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string CollectData(bool isDraft)
        {
            DocumentXML objInfo = new DocumentXML();
            DataSet ds = CreateData(isDraft);
            if (ds != null)
            {
                Session["SODATA"] = ds.Copy();
                if (isDraft)
                {
                    ds.Tables["ODRF"].Columns.Remove("OutletCode");
                    ds.Tables["DRF1"].Columns.Remove("ShipType");
                    ds.Tables["DRF1"].Columns.Remove("TrnspName");
                    return objInfo.ToXMLStringFromDS("112", ds);
                }
                else
                {
                    ds.Tables["OPOR"].Columns.Remove("OutletCode");
                    ds.Tables["POR1"].Columns.Remove("ShipType");
                    ds.Tables["POR1"].Columns.Remove("TrnspName");
                    return objInfo.ToXMLStringFromDS("22", ds);
                }
            }
            return string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isDraft"></param>
        /// <returns></returns>
        public DataSet CollectDataPO(bool isDraft)
        {
            return CreateData(isDraft);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isDraft"></param>
        /// <returns></returns>
        private DataSet CreateData(bool isDraft)
        {
            try
            {
                DataTable tb = ((DataTable)Session["POTable"]);
                if (tb != null && tb.Rows.Count > 0)
                {
                    DocumentXML objInfo = new DocumentXML();
                    DataSet ds = new DataSet("DS");

                    DataTable tblHeader = new DataTable("OPOR");
                    tblHeader.Columns.Add("CardCode");
                    tblHeader.Columns.Add("CardName");
                    tblHeader.Columns.Add("DocDate");
                    tblHeader.Columns.Add("DocDueDate");
                    tblHeader.Columns.Add("U_AB_PORemarks");
                    tblHeader.Columns.Add("OutletCode");
                    tblHeader.Columns.Add("U_AB_Urgent");
                    tblHeader.Columns.Add("U_AB_ID_User");
                    tblHeader.Columns.Add("U_AB_POWhsCode");
                    if (this.hdnIsUpdate.Value == "0")
                    {
                        tblHeader.Columns.Add("U_AB_SentSupplier");
                    }


                    DataRow row = tblHeader.NewRow();
                    row["CardCode"] = this.txtVendorCode.Text;
                    row["DocDate"] = DateTime.Now;
                    row["DocDueDate"] = DateTime.Now;
                    
                    
                    row["U_AB_UserCode"] = Session[Utils.AppConstants.ID_User] != null ? Session[Utils.AppConstants.ID_User].ToString() : "";
                    
                    
                    if (this.hdnIsUpdate.Value == "0")
                    {
                        row["U_AB_SentSupplier"] = "N";
                    }
                    //Save As Draft
                    if (isDraft)
                    {
                        tblHeader.Columns.Add("ObjType");
                        row["ObjType"] = "22";
                        tblHeader.TableName = "ODRF";
                    }

                    tblHeader.Rows.Add(row);

                    DataTable tblItem = new DataTable();
                    if (!isDraft)
                    {
                        tblItem.TableName = "POR1";
                    }
                    else
                    {
                        tblItem.TableName = "DRF1";
                    }
                    tblItem.Columns.Add("ItemCode");
                    tblItem.Columns.Add("Dscription");
                    tblItem.Columns.Add("UnitMsr");
                    tblItem.Columns.Add("Quantity");
                    tblItem.Columns.Add("Price");
                    tblItem.Columns.Add("LineTotal");
                    tblItem.Columns.Add("Vatgroup");
                    tblItem.Columns.Add("ShipType");
                    tblItem.Columns.Add("TrnspName");
                    tblItem.Columns.Add("WhsCode");
                    tblItem.Columns.Add("U_AB_POQty");
                    if (isDraft)
                    {
                        tblItem.Columns.Add("PriceBefDi");
                    }
                    foreach (DataRow r in tb.Rows)
                    {
                        DataRow rowNew = tblItem.NewRow();
                        rowNew["ItemCode"] = r["ItemCode"];
                          //Save As Draft
                        if (isDraft)
                        {
                            if (double.Parse(r["Quantity"].ToString()) == 0)
                            {
                                rowNew["Quantity"] = "0.001";
                            }
                            else
                            {
                                rowNew["Quantity"] = r["Quantity"];
                            }
                            rowNew["LineTotal"] = decimal.Parse(rowNew["Quantity"].ToString()) * decimal.Parse(r["Price"].ToString());
                            rowNew["PriceBefDi"] = r["Price"];
                        }
                        else
                        {
                            rowNew["Quantity"] = r["Quantity"];
                            rowNew["LineTotal"] = r["LineTotal"];
                        }
                        rowNew["Dscription"] = r["Dscription"];
                        rowNew["UnitMsr"] = r["BuyUnitMsr"];
                        rowNew["Price"] = r["Price"];
                        rowNew["ShipType"] = r["ShipType"];
                        rowNew["TrnspName"] = r["TrnspName"];
                        rowNew["U_AB_POQty"] = r["Quantity"];
                        rowNew["Vatgroup"] = r["VatgroupPu"];
                        
                        if (!isDraft)
                        {
                            if (double.Parse(r["Quantity"].ToString()) != 0)
                            {
                                tblItem.Rows.Add(rowNew);
                            }
                        }
                        else
                        {
                            tblItem.Rows.Add(rowNew);
                        }
                    }

                    ds.Tables.Add(tblHeader);
                    ds.Tables.Add(tblItem);
                    MasterData obj = new MasterData();
                    string errMsg = string.Empty;
                    if (!isDraft)
                    {
                        if (this.hdnIsUpdate.Value == "0")
                        {
                            //errMsg = obj.CheckAddPO(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(),
                            //                   _companyCode, ds, DateTime.Now, false, string.Empty);
                        }
                        else
                        {
                            //errMsg = obj.CheckAddPO(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(),
                            //              _companyCode, ds, DateTime.Now, true, _docEntry);
                        }
                        if (errMsg.Length > 0)
                        {
                            if (errMsg.Trim() == "The device is not ready.")
                            {
                                errMsg = "System is processing another request. Pls try again later.";
                            }
                            this.lblError.Text = errMsg;
                            this.lblError.Visible = true;
                        }
                        else
                        {
                            DataTable tbAddress = new DataTable();
                            tbAddress.TableName = "POR12";
                            tbAddress.Columns.Add("StreetS");
                            tbAddress.Columns.Add("BlockS");
                            tbAddress.Columns.Add("CityS");
                            tbAddress.Columns.Add("CountryS");
                            tbAddress.Columns.Add("ZipCodes");

                            
                            return ds;
                        }
                    }
                    else
                    {
                        return ds;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
                if (this.hdnStatus.Value == "C")
                {
                    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
                    txtQuantity.Enabled = false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               
            }
            catch
            {
            }
            UpdatePrice();
        }
        /// <summary>
        /// 
        /// </summary>
        private void ResetPage()
        {
            this.txtVendorCode.Text = "";
            
            this.Session["ChosenItem"] = null;
            this.Session["ChosenVendorCode"] = null;
            this.Session["ChosenVendorName"] = null;
            Session["SODATA"] = null;
            LoadOrderWareHouse();
            LoadData();
            this.btnSaveDraft.Enabled = false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveDraft_Click(object sender, EventArgs e)
        {
            try
            {
                /*CheckDate();
                this.lblError.Visible = false;
                string requestXML = CollectData(true);
                if (requestXML == "") return;
                Transaction ts = new Transaction();
                DataSet ds = new DataSet();
                //Create New Draft
                if (this.hdnIsUpdate.Value == "0")
                {
                    ds = ts.CreateMarketingDocument(requestXML, Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(),
                                       _companyCode, "112", "", false);
                }
                //Update Draft
                else if (this.hdnIsUpdate.Value == "1")
                {
                    ds = ts.CreateMarketingDocument(requestXML, Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(),
                                  _companyCode, "112", _docEntry, true);
                }
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    this.lblError.Text = ds.Tables[0].Rows[0]["ErrMsg"].ToString();
                }
                else
                {
                    this.lblError.Text = "Operation complete successful!";
                    if (this.hdnIsUpdate.Value == "0")
                    {
                        ResetPage();
                    }
                }*/
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction obj = new Transaction();
                string error = string.Empty;
                if (_isPO == "1")
                {
                    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
                }
                else
                {
                    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
                }
                if (error.Length == 0)
                {
                    this.lblError.Text = "Operation complete successful!";
                    DisableControl();
                }
                else
                {
                    this.lblError.Text = error;
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }
    }
}